package luanvan.app.foodnote;

import java.util.ArrayList;
import java.util.List;


import luanvan.app.foodnote.library.GMapV2Direction;
import luanvan.app.foodnote.library.googledirections.JsonParser;
import luanvan.app.foodnote.library.googledirections.Parser;
import luanvan.app.foodnote.library.googledirections.Route;
import luanvan.app.foodnote.library.googledirections.Segment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

public class DirectionsActivity extends SherlockFragmentActivity implements LocationListener {
	
	private final static String MODE_DRIVING = "driving";
	private final static String MODE_WALKING = "walking";  
	
	private static final int TEN_METERS = 10;
    private static final int TWO_MINUTES = 1000 * 60 * 2;
    
    private static final String TAG_LATITUDE = "LATITUDE";
    private static final String TAG_LONGITUDE = "LONGITUDE";
    
    private PolylineOptions pathLine; 
    
    private double lat, lng;
    private double latExtra, lngExtra;

	private LocationManager locationManager;

	GoogleMap mMap;
    GMapV2Direction md;
    
	LatLng fromPosition, toPosition;
	
	ListView listDirections;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.directions);
        
        listDirections = (ListView) findViewById(R.id.list_direction);
        
        Intent intent = getIntent();
        latExtra = intent.getExtras().getDouble(TAG_LATITUDE);
        lngExtra = intent.getExtras().getDouble(TAG_LONGITUDE);
        
        toPosition = new LatLng(latExtra, lngExtra);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
 		Location location = locationManager
 				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
 		if(location != null){
 			this.onLocationChanged(location);
 			fromPosition = new LatLng(location.getLatitude(), location.getLongitude());
 		}
        
        md = new GMapV2Direction();
		mMap = ((SupportMapFragment)getSupportFragmentManager()
						.findFragmentById(R.id.mapDirection)).getMap();

		LatLng coordinates = fromPosition;		
		mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 16));
		
		mMap.addMarker(new MarkerOptions().position(fromPosition).title("Vị trí hiện tại"));
		mMap.addMarker(new MarkerOptions().position(toPosition).title("Điểm đến"));

		Route route = drawPath(fromPosition, toPosition, MODE_DRIVING);
		
		List<LatLng> list = route.getPoints();
		List<Segment> listSegment = route.getSegments();
		
		ArrayList<String> listDir = new ArrayList<String>();
		
		for(int i = 0; i < listSegment.size(); i++){
			
			String instruct = listSegment.get(i).getInstruction();
			double dist = listSegment.get(i).getDistance();
			int lenght = listSegment.get(i).getLength();
			
			listDir.add(instruct);
			
			Log.e("Segment", instruct + " ,Dist " + String.valueOf(dist) + ", Lenght " + String.valueOf(lenght));
			Log.e("XXXXX", "Point No: " + list.size() + ", " + route.getName());
		}
		if(!listDir.isEmpty()){
			/*ArrayAdapter<String> adapterDir = new ArrayAdapter<String>(this, R.layout.direction_items, listDir);
			listDirections.setAdapter(adapterDir);*/
		}
		
		if(pathLine != null) pathLine = null;
		pathLine = new PolylineOptions();
		pathLine.width(4);
		pathLine.addAll(list);
		pathLine.color(Color.rgb(0,191,255));
		
		mMap.addPolyline(pathLine);
		
    }
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu_direction, menu);
		
        return super.onCreateOptionsMenu(menu);
	}
	@Override
	protected void onResume(){
		super.onResume();
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, TWO_MINUTES, TEN_METERS, this);
	}
	@Override
	protected void onDestroy(){
		super.onDestroy();
		locationManager.removeUpdates(this);
	}
	@Override
	public void onLocationChanged(Location location) {
		lat = location.getLatitude();
		lng = location.getLongitude();
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}
	
	 private Route drawPath(LatLng start, LatLng dest, String mode) {
         Parser parser;
         String jsonURL = "http://maps.google.com/maps/api/directions/json?";
         final StringBuffer sBuf = new StringBuffer(jsonURL);
         sBuf.append("origin=");
         sBuf.append(start.latitude);
         sBuf.append(',');
         sBuf.append(start.longitude);
         sBuf.append("&destination=");
         sBuf.append(dest.latitude);
         sBuf.append(',');
         sBuf.append(dest.longitude);
         sBuf.append("&sensor=true&mode=");
         sBuf.append(mode);
         parser = new JsonParser(sBuf.toString());
         Route r =  parser.parse();
         return r;
     }
}
